/**
 * 历史轨迹回放类
 */

HistoryRoutePanel = {};
HistoryRoutePanel._isOver = true;//播放结束标志
HistoryRoutePanel._isPlay = false;//正在播放的状态
HistoryRoutePanel.timerId = null;//定时器ID
HistoryRoutePanel.playSpeed = 200;//播放速度,
HistoryRoutePanel._autoChangePage = true;//自动翻页播放
HistoryRoutePanel.totalNum = 0;//总记录数
HistoryRoutePanel.maxTimeSpan = 300;//最大播放间隔,每隔200ms，播放一次
HistoryRoutePanel.ByAreaAndTime = false;//定时定区域轨迹查询
HistoryRoutePanel.showRouteBeforePlay = true;
HistoryRoutePanel.playOrder = true;//定义播放顺序，如果为true，则为正常播放，如果为false，则为倒放
HistoryRoutePanel.vehicleStopPointShow = false;//定义停车点显示标记，默认为false，即不显示，如果为true，则为显示

//设置播放顺序
HistoryRoutePanel.setPlayOrder = function(value){
	this.playOrder = value;
}

//设置停车点显示标记
HistoryRoutePanel.setShowVehicleStopPoint = function(value){
	this.vehicleStopPointShow = value;
}

//返回地图对象
HistoryRoutePanel.getRouteMapHandler = function()
{
	return this.routeMapHandler;
}
//查询开始时间
HistoryRoutePanel.getStartTime = function()
{
	var startTime = $("#routeStartTime").datetimebox('getText');
	return startTime;
}
//查询结束时间
HistoryRoutePanel.getEndTime = function()
{
	var endTime = $("#routeEndTime").datetimebox('getText');
	return endTime;
}

				

//设置查询条件中的车牌号输入控件
HistoryRoutePanel.setPlateNo = function(plateNo)
{
	//$("#routePlateNo").val(plateNo);
	$("#routePlateNo").textbox('setValue',plateNo);
}


HistoryRoutePanel.isButtonDisabled = function(btnId)
{
	var opts = $("#"+btnId).linkbutton("options");
	return   true == opts.disabled;
}

HistoryRoutePanel.setButtonText = function(btnId,txt)
{
	$("#"+btnId+" .l-btn-text").html(txt);
}


HistoryRoutePanel.resetButton = function()
{
	HistoryRoutePanel.setButtonText("btnQueryHisData","查询");
	$("#btnQueryHisData").linkbutton('enable');
	$("#btnPlayRoute").linkbutton('disable');
	$("#btnPauseRoute").linkbutton('disable');
	$("#btnStopPlayRoute").linkbutton('disable');
}

/**
 * 历史轨迹页面初始化
 */
HistoryRoutePanel.init = function()
{
	var me = this;
	
	this.createhistoryRouteGrid();
	this.createVehicleStopInfo();//设置停车记录
	this._playButton = $("#btnPlayRoute");
	//  this._playButton.html("播放");
	//查询按钮
	$("#btnQueryHisData").click(function()
	{
		var plateNo = $("#routePlateNo").textbox("getText");
		if(plateNo== null || plateNo.length == 0)
		{
			$.messager.alert("提示","请输入有效车牌号!");
			return;
		}
		if(me.isButtonDisabled("btnQueryHisData"))
			return;
	   
		
		HistoryRoutePanel.setProgress(0);//初始化进度条为0
		HistoryRoutePanel.queryHistoryRoute();//查询历史轨迹数据
		HistoryRoutePanel.queryVehicleStopInfo();//查询停车记录
		
	});
	//播放轨迹的按钮点击事件
	$("#btnPlayRoute").click(function()
	{
		if(me.isButtonDisabled("btnPlayRoute"))
			return;
		me.play();
	});
	$("#btnStopPlayRoute").click(function()
	{
		if(me.isButtonDisabled("btnStopPlayRoute"))
			return;
		me.stopPlay();
	});
	
	$("#btnPauseRoute").click(function()
	{
		if(me.isButtonDisabled("btnPauseRoute"))
			return;
		me.pause();
	});

	//excel导出
	$("#btnExportHisData").click(function()
	{
		me.exportExcel();
	});
	//播放速度滑块
	$('#playSpeedSlider').slider({
		value:1,showTip:true,
		tipFormatter: function(value){    
			//var speed = me.maxTimeSpan - parseInt(value);
			var descr = "慢";
			if(value > 60)
				descr = "快";
			else if(value > 40)
				descr = "中";
			return descr;    
		},
		onChange: function(value){
			me.playSpeed = me.maxTimeSpan * (110 - parseInt(value)) / 100;

		}
	})
    var me = this;
	$("#cbDisplayHisData").click(function()
	{
		//判断是否已经打勾
		if($("#cbDisplayHisData").attr('checked')=="checked"){
	         $('#hisRouteLayout').layout('expand','south');
			 //var tab = $("#hisDataTab").tabs("getTab",0);
			 //var width = tab.width();
			 //var height = tab.height();
		    // me.hisDataGrid.datagrid('resize',{width:width-1,height:height-1,left:0,top:0});
		} else
		{
	         $('#hisRouteLayout').layout('collapse','south');
		}
	});
	$('#hisRouteLayout').layout('collapse','south');

	//this.createhistoryRouteGrid(gridId);
	//设置在线地图路径
	var mapUrl = globalConfig.mapPath;
	if(mapUrl.indexOf('?') < 0)
		mapUrl += '?hisRoute=true';
	else
		mapUrl += '&hisRoute=true';
	$("#routeMapFrame").attr("src", mapUrl);
	
	
	//日期类型拉框触发事件，快捷的选择日期
		$('#selDateOption').combobox(
		{
			onChange :function(newValue,oldValue){ 
				var filterType = newValue;
	            var now = Utility.today();
				if(filterType == "1")
				{
					//当天
					var startTime = now + " 00:00:00";
					var endTime = now + " 23:59:00";
					$("#routeStartTime").datetimebox('setValue', startTime)  ;
					$("#routeEndTime").datetimebox('setValue', endTime);

				}else if(filterType == "2")
				{
					//昨天
					var now = new Date();
	                var date1 = new Date(now.getFullYear(),now.getMonth(),now.getDate());
					date1 = Utility.addDay(date1,-1);
					var yesterday = Utility.dateToString(date1, "yyyy-MM-dd");;
					var startTime = yesterday + " 00:00:00";
					var endTime = yesterday + " 23:59:00";
					$("#routeStartTime").datetimebox('setValue', startTime)  ;
					$("#routeEndTime").datetimebox('setValue', endTime);
				}else if(filterType == "3")
				{
					//前天
					var now = new Date();
	                var date1 = new Date(now.getFullYear(),now.getMonth(),now.getDate());
					date1 = Utility.addDay(date1,-2);
					var yesterday = Utility.dateToString(date1, "yyyy-MM-dd");
					var startTime = yesterday + " 00:00:00";
					var endTime = yesterday + " 23:59:00";
					$("#routeStartTime").datetimebox('setValue', startTime)  ;
					$("#routeEndTime").datetimebox('setValue', endTime);

				}else if(filterType == "4")
				{
					//最近一天
					var date1 = new Date();
					var endTime = Utility.dateToString(date1, "yyyy-MM-dd HH:mm:ss");
					
					date1 = Utility.addDay(date1,-1);
					var startTime = Utility.dateToString(date1, "yyyy-MM-dd HH:mm:ss");

					$("#routeStartTime").datetimebox('setValue', startTime)  ;
					$("#routeEndTime").datetimebox('setValue', endTime);
				}else if(filterType == "5")
				{
					//最近一天
					var date1 = new Date();
					var endTime = Utility.dateToString(date1, "yyyy-MM-dd HH:mm:ss");
					
					date1 = Utility.addDay(date1,-2);
					var startTime = Utility.dateToString(date1, "yyyy-MM-dd HH:mm:ss");

					$("#routeStartTime").datetimebox('setValue', startTime)  ;
					$("#routeEndTime").datetimebox('setValue', endTime);
				}
		    }
		});

	//当选择开始时间的时候，自动检测日期段天数只差，如果超过2天，则自动修改结束时间，
	//使其最大天数差保持为2.
	$("#routeStartTime").datetimebox({'onSelect': function(date)
	{
	   var strEndTime = $("#routeEndTime").datetimebox('getText');
	   startTime = date;
	   endTime = Utility.stringToDate(strEndTime);
	   if(isNaN( startTime.getTime() ) || isNaN(endTime.getTime() ) )
	   {
			$.messager.alert('提示','非法的日期格式'); 
	   }
	   var  iDays = Utility.getDay(startTime,endTime);  
	   if(iDays > 2 || iDays <= 0)
	   {
		   endTime = startTime;
		   //endTime = Utility.addDay(endTime,1);//加一天
		   var strEndTime = Utility.dateToString(endTime, "yyyy-MM-dd") + " 23:59:00";
		   $("#routeEndTime").datetimebox('setValue', strEndTime)  ;
	   }
		
	}})  ;

	
	var now = Utility.today();
	var startTime = now + " 00:00:00";
	var endTime = now + " 23:59:00";
	$("#routeStartTime").datetimebox('setValue', startTime)  ;
	$("#routeEndTime").datetimebox('setValue', endTime);
}
/**
 * 根据查询条件进行excel导出
 */
HistoryRoutePanel.exportExcel = function()
{
	var routeForm = $('#routeForm');
	 var queryUrl =  globalConfig.webPath+'/historyGpsInfo/list.action';
	 this.routeMapHandler = this.getHisMapHandler();
	 //this.routeMapHandler.clearHisRoute();
	 routeForm.form({
		url:queryUrl,
		onSubmit: function(){
			//进行表单验证
			//如果返回false阻止提交
			var isValid =   routeForm.form('validate'); 
			if(isValid)
			{
				var plateNo = $("#routePlateNo").textbox('getText');
				var startTime = $("#routeStartTime").datetimebox('getValue')  ;
				var endTime = $("#routeEndTime").datetimebox('getValue');
				var minSpeed = $("#minSpeed").val();
				var excelFileName="GPS历史轨迹";
				var queryParams = {queryId:"gpsInfo.selectHisotryGpsInfos",
							fileName:excelFileName,
					plateNo:plateNo,startTime:startTime,endTime:endTime,minSpeed:minSpeed};
			    var strParam = jQuery.param(queryParams);
				var url = globalConfig.webPath + "/historyGpsInfo/export.action?"+strParam;
						//openWindow(url, 300,300,"");
				window.open(url);
			}
			return false;
		},
		success:function(data){
			//alert(data)
			//me.hisDataGrid.datagrid("loadData",data);
		}
	});
	//提交表单
	$('#routeForm').submit();
}



/**
 * 历史轨迹数据分页表格
 */
HistoryRoutePanel.createhistoryRouteGrid = function()
{
	var me = this;
	//if(this.hisDataGrid)
		//return;
	var queryParams = {};//{plateNo:"测A00003",startTime:"2014-09-29 1:1:1",endTime:"2014-09-29 23:1:1"};
	var queryUrl =  globalConfig.webPath+'/historyGpsInfo/list.action';
	var gridId = "hisDataGrid";
	this.hisDataGrid=	$("#"+gridId);
    this.hisDataGrid.datagrid({
                columns: [[
				   { title: '车牌号', field: 'plateNo', width: 70,minWidth:70 },
				   { title: '车机时间', field: 'sendTime', width: 140,minWidth:120 },
				   { title: '上报时间', field: 'createDate', width: 140,minWidth:120 },
                    { title: '位置', field: 'location', width: 300,minWidth:240 },
                    { title: '状态', field: 'status',formatter:formatStatusInfo, width: 80,minWidth:80 },
					{ title: '速度', field: 'velocity', width: 40,minWidth:40 },
					{ title: '报警信息', field: 'alarmTypeName',formatter:formatAlarmTypeData, width: 80,minWidth:80 },
                    { title: '方向', field: 'directionDescr', width: 50,minWidth:50 },
                    { title: '里程', field: 'mileage', width: 70,minWidth:60 },
                    { title: '有效性', field: 'valid', width: 60,minWidth:40 },
                    { title: '海拔', field: 'altitude', width: 60,minWidth:40 },
                    { title: '经度', field: 'longitude', width: 110, isSort: false,minWidth:80 },
                    { title: '纬度', field: 'latitude', width: 110, isSort: false,minWidth:80 },
					{ title: '所属车组', field: 'depName', width: 90,minWidth:80 }
					
					/*
					{ title: '脉冲速度', field: 'recordVelocity', width: 40,minWidth:40 },
					{ title: '油量', field: 'gas', width: 40,minWidth:60 },
                    { title: 'sim卡号', field: 'simNo', width: 120,minWidth:80 },
                    { title: '颜色', field: 'plateColor', width: 40,minWidth:40 },
                    { title: '原始经度', field: 'orgLongitude', width: 0},
                    { title: '原始纬度', field: 'orgLatitude', width: 0 }*/
                    ]],
                //height: 150,
				fit:true,
				//url: queryUrl,
				method: 'POST',
				queryParams: queryParams,
				//idField: 'gpsId',
				striped: true,
				fitColumns: false,
				autoRowHeight:false,
				singleSelect: true,
				rownumbers: true,
				//pagination: true,
				//loadFilter:pagerFilter, //内存分页，必须要指定过滤器
				nowrap: true,
				//pageSize: 50,
				//pageList: [10, 20, 50, 100, 150, 200],
				showFooter: true,
				onBeforeLoad:function(param)
				{
					//在没有输入查询参数前，不查询
					if(param.plateNo)
					  return true;
				    else
					  return false;
				},onLoadSuccess:function(data)
				{
					
					if(data.rows && data.rows.length > 0)
					 {
					   //HistoryRoutePanel.startPlayRoute(data); //开始画轨迹
					}else
					{
						HistoryRoutePanel.resetButton();
						 $.messager.alert('提示','该时间段没有历史轨迹数据');
						 return;
					}
				},
				onDblClickRow:function(rowIndex,rowData){
					console.log("双击第" + (rowIndex) + " 行");
					console.log(rowData);
					//设置停车点为地图中心
					if(me.routeMapHandler == null){
						return;
					}
					me.routeMapHandler.setCenter(rowData.latitude, rowData.longitude);
					me.routeMapHandler.drawRoute(rowData);//设置轨迹
				},
            });
			
     return this.hisDataGrid;	
}


/*
添加停车记录表格窗体
*/
HistoryRoutePanel.createVehicleStopInfo = function(){
	var me = this;
	// console.log("添加停车记录窗体");
	var gridId = "parkingGrid";
	this.vehicleStopInfoGrid=	$("#"+gridId);
	this.vehicleStopInfoGrid.datagrid({
		columns: [[
			{ title: '车牌号', field: 'plateNo', width: 80, minWidth: 70 },
			{ title: '开始时间', field: 'startTime', width: 140, minWidth: 70 },
			{ title: '结束时间', field: 'endTime', width: 140, minWidth: 120 },
			{ title: '停车时长(分钟)', field: 'createDate',formatter:formatVehicleStopTimeLong, width: 140, minWidth: 120 },
			{ title: '地址', field: 'location', width: 300, minWidth: 240 },
			{ title: '附近', field: 'location1', width: 120, minWidth: 240 },
		]],
		fit: true,
		striped: true,
		fitColumns: false,
		autoRowHeight: false,
		singleSelect: true,
		rownumbers: true,
		//pagination: true,
		//loadFilter:pagerFilter, //内存分页，必须要指定过滤器
		nowrap: true,
		//pageSize: 50,
		//pageList: [10, 20, 50, 100, 150, 200],
		showFooter: true,
		onDblClickRow:function(rowIndex,rowData){
			console.log("双击第" + (rowIndex) + " 行");
			// console.log(rowData);
			//设置停车点为地图中心
			if(me.routeMapHandler == null){
				return;
			}
			me.routeMapHandler.setCenter(rowData.latitude, rowData.longitude);
		},
	});
}

/*
格式化停车时长
	1.获取开始时间和结束时间
*/
function formatVehicleStopTimeLong(value,rowData,rowIndex){
	var result = -1;
	try {
		if(rowData){

			// rowData.remarks = "测试代码";
			rowData.stopTimeValue = '';
			rowData.rowIndex2 = rowIndex+1;
			var startTime = new Date(rowData.startTime);
			var start = startTime.getTime();
			var endTime = new Date(rowData.endTime);
			var end = endTime.getTime();
			var cout = parseInt(end - start);
			// console.log("停车时长为 ：" + cout);
			if(!isNaN(cout)){
				cout = parseInt(cout/1000);
				var returnValue = Math.floor(cout/60) + "分";
				returnValue += Math.floor(cout%60) + "秒";
				rowData.stopTimeValue = returnValue;//赋值
				result =  returnValue;
			}
		}
		if(result == -1){
			result = "";
		}
	} catch (error) {
		console.error("格式化停车时长错误 ： " + error);
	}
	return result;
}

/*
格式化状态信息数据
	只保留定位和acc信息
*/
function formatStatusInfo(value, rowData, rowIndex){
	// console.log(value);
	var temp = '' + value;
	// temp = "ACC关，未定位，无报警，其他状态";

	//根据字数不同，截取不同长度的字符串
	if(temp.indexOf("未定位") >= 0){
		temp = temp.substring(0,8);
	}else{
		if(temp.indexOf("定位") >= 0){
			temp = temp.substring(0,7);
		}
	}
	return temp;
} 

/*
格式化报警类型信息
*/
function formatAlarmTypeData(value,rowData,rowIndex){
	var activeAlarmName =  "主动安全报警";
	if(value == undefined){
		return "";
	}else{
		if(value != ""){
			// console.log(rowData.alarmData.alarmSourceName);
			// console.log(activeAlarmName);
			var activeFlg = -1;
			var valueTemp = '';
			if(rowData.alarmData.alarmSourceName == activeAlarmName){
				activeFlg = 1;
				valueTemp = rowData.alarmData.alarmIndex;
			}else{
				activeFlg = 0;
				valueTemp = rowData.alarmData.id;
			}
			var str = value;//设置显示原文字
			// var str = '<a href="javascript:void(0)" onclick="javascript:showHistoryAlarmInfo(&quot;' +valueTemp +'&quot;,' + activeFlg + ')">' + value + '</a>';
			return str;
		}else{
			return value;
		}
	}
}

function showHistoryAlarmInfo(valueTemp,activeFlg){
	console.log('是否主动安全报警标记 ：' + activeFlg);
	console.log("索引值为 ： " + valueTemp);

}


//设置历史轨迹播放的进度
HistoryRoutePanel.setProgress = function(value)
{
	// $('#routeProgressbar').progressbar('setValue', value);
	$('#routeProgressbar2').slider('setValue', value);
}

/**
 * 查询历史轨迹,在ajax请求成功后，回掉播放方法startPlayRoute()
 */
 HistoryRoutePanel.queryHistoryRoute = function()
 {
	// this.createhistoryRouteGrid();
	 var me = this;
	 var routeForm = $('#routeForm');
	 var isValid =   routeForm.form('validate'); 
	 if(isValid == false ||  me.validateDate() ==false)
			{
				return;
			}
	 var queryUrl =  globalConfig.webPath+'/historyGpsInfo/list.action';
	 this.routeMapHandler = this.getHisMapHandler();
	 this.routeMapHandler.clearHisRoute();
	 var isChecked = $("#cbShowRouteBeforePlay").attr('checked');
	 me.routeMapHandler.showRouteBeforePlay=(isChecked=="checked");
     var plateNo = $("#routePlateNo").textbox('getText');
	 var startTime = $("#routeStartTime").datetimebox('getText');
	 var endTime = $("#routeEndTime").datetimebox('getText');
	 var minSpeed = $("#minSpeed").val();
	 var queryParams = {plateNo:plateNo,startTime:startTime,endTime:endTime,minSpeed:minSpeed};
	 $.messager.progress({ 
					text: '正在加载历史轨迹数据' 
				});

     $("#hisMileage").html("");//清除里程显示
	 $.ajax({
            type: "POST",
            url: queryUrl,
			data:queryParams,
			error:function(){
			   //alert("网络连接错误，无法读取数据!");
               //Utility.done();
			},
            success: function(data){
				$.messager.progress('close'); //解除遮罩
				var result=data;//eval("("+strReult+")");  
				if(result.success)
				{
					if(result.data && result.data.length > 0)
					{
					    var dataLen = result.data.length;
					    var startMileage= result.data[0].mileage;
					    var endMileage =result.data[dataLen - 1].mileage;
						var totalMileage = endMileage - startMileage;
						$("#hisMileage").html("行驶总里程:" + totalMileage.toFixed(1) + "公里");
					}
					//var data = {rows:result.data};
					var rowDatas = result.data;
					me.initHisdata(rowDatas);//初始化数据
					//请求成功后，继续请求报警数据，并且接收到报警数据后填充到数组中
					me.hisDataGrid.datagrid("loadData", rowDatas);
					me.startPlayRoute(rowDatas);
					me.pause();
					//加载播放信息
					me.queryHistoryAlarmDatas(rowDatas,queryParams);

					
				}else
				{
					me.resetButton();//重新恢复按钮可用性
					alert(result.message);
				}
			},
			error:function()
		    {
				me.resetButton();//重新恢复按钮可用性
				$.messager.progress('close'); 
			}
	 });

 }


/*
查询停车记录数据
	 1.根据条件，从数据库中请求停车记录数据
	 2.获取数据后，填充到表格中
*/
HistoryRoutePanel.queryVehicleStopInfo = function(){
	// console.log("开始获取停车记录数据并进行格式化............");
	var me = this;

	var plateNo = $("#routePlateNo").textbox('getText');
	var startTime = $("#routeStartTime").datetimebox('getText');
	var endTime = $("#routeEndTime").datetimebox('getText');
	var param = { plateNo: plateNo, startTime: startTime, endTime: endTime};

	var url = globalConfig.webPath + "/historyGpsInfo/getVehicleStopInfo.action";//请求地址
	Utility.getAjaxData(url,JSON.stringify(param),function(result){
		// console.log("接收到获取的停车记录数据");
		// console.log(result);
		if(result.success){
			var rowDatas = result.data;
			me.vehicleStopInfoGrid.datagrid("loadData",rowDatas);

			//绘制停车点
			// console.log(me.routeMapHandler);
			// console.log("停车点绘制标记 ：" + me.vehicleStopPointShow);
			if(me.vehicleStopPointShow){//如果true，绘制停车点
				if(me.routeMapHandler == null){
					return;
				}
				// console.log("调用地图对象，绘制停车点");
				if(typeof(me.routeMapHandler.drawVehicleStop) == "function"){
					me.routeMapHandler.drawVehicleStop(rowDatas);	 
				}
			}
		}else{

		}
	});
}


 /*
 初始化数据
 */
 HistoryRoutePanel.initHisdata = function(rowDatas){
	//  console.log("初始化历史轨迹数据.......");
	//  console.log(rowDatas);
	$.each(rowDatas,function(i,rowData){
		rowData.alarmTypeName = "";
	});
 }
 /*
 请求历史轨迹时间段中的报警记录
	 1.查询alarm和adasAlarm表中的报警记录
	 2.接收到报警数据后，格式化到数据中
 */
 HistoryRoutePanel.queryHistoryAlarmDatas = function(rowDatas,param){
	 var me = this;
	//  console.log("开始请求历史轨迹时间段中的报警记录.......");
	//  console.log(rowDatas);

	 //获取报警数据
	 var url = globalConfig.webPath + "/activeSafeAlarm/getAdasAlarmByPlateNoFromAdasAlarm.action";//请求地址
	 Utility.getAjaxData(url,JSON.stringify(param),function(data){
		//  console.log("接收到请求轨迹回放报警数据返回信息");
		//  console.log(data);
		 if(data.success){
			
			//  console.log("获取轨迹回放报警数据成功");
			 var alarms = data.data;
			 if(alarms.length > 0){
				// var rowDatas = me.hisDataGrid.datagrid("getData");
				// rowDatas = rowDatas.rows;
				$.each(alarms, function (i, datas) {
					if (datas.length > 0) {
						$.each(datas, function (n, dataTemp) {
							var temp = Utility.getOneAlarmSourceData(dataTemp.alarmSource, dataTemp.alarmType);
							dataTemp.alarmTypeName = temp.alarmTypeName;
							dataTemp.alarmSourceName = temp.alarmSourceName;
							// console.log(dataTemp);
							me.setAlarmInfo(rowDatas,dataTemp);
						});
					}
				});
				//如果需要更新，则更新数据
				// console.log("开始重置数据");
				// console.log(rowDatas);
				me.hisDataGrid.datagrid("loadData",rowDatas);
				// me.startPlayRoute(rowDatas);
				// me.pause();
			}
		 }
	 });
 }

 /*
 根据createDate获取报警数据的位置并更新
 */
 HistoryRoutePanel.setAlarmInfo = function(rowDatas,alarmData){
	var createDateTemp = alarmData.createDate;
	// console.log(rowDatas);
	if(createDateTemp != ""){
		// console.log("开始查找位置");
		$.each(rowDatas,function(n,rowData){
			if(rowData.createDate == createDateTemp){
				//查询到信息
				// console.log("查找到数据，在第 " + (n+1) + " 行");
				rowData.alarmData = alarmData;
				rowData.alarmTypeName = alarmData.alarmTypeName;
			}
		});
	}
 }


  HistoryRoutePanel.validateDate = function()
 {
	   var startTime = $("#routeStartTime").datetimebox('getText');
	   var endTime = $("#routeEndTime").datetimebox('getText');
	    startTime = Utility.stringToDate(startTime);
	   endTime = Utility.stringToDate(endTime);
	   if(isNaN( startTime.getTime() ) || isNaN(endTime.getTime() ) )
	   {
			$.messager.alert('提示','非法的日期格式'); 
	   }
	   var today = new Date();

	   var date1 = new Date(startTime.getFullYear(),startTime.getMonth(),startTime.getDate());
	   var date2 = new Date(endTime.getFullYear(),endTime.getMonth(),endTime.getDate());
		if(startTime > today)
		{
			$.messager.alert('提示','开始日期不能大于当前日期'); 
			return false;
		}
		if(startTime >= endTime)
		{
			$.messager.alert('提示','开始时间不能大于等于结束时间'); 
			return false;
		}

		var  iDays = Utility.getDay(date1,date2);  
		if(iDays > 4)
		{
			$.messager.alert('提示', '一次只能查询不超过四天的历史数据'); 
			return false;
		}
		return true;
 }

 //重新回到第一页播放
 HistoryRoutePanel.firstPage = function()
 {
	 this.hisDataGrid.datagrid("load");
 }

 HistoryRoutePanel.nextPage = function()
 {
	 //this.hisDataGrid.datagrid('getPager').pagination({pageNumer:2});
	 //$(".pagination-next")
	 //this.hisDataGrid.datagrid('reload');
	 var p = this.hisDataGrid.datagrid('getPager');
	 var p1 = p.find(".pagination-next");
	 p1.click();
	 //p.find(".pagination-next]").click();
	 //p.selectPage(
 }

HistoryRoutePanel.getCurPageData = function()
{
	return this.hisDataGrid.datagrid('getRows');
}

HistoryRoutePanel.getCurRowData = function()
{
	return this.hisDataGrid.datagrid('getSelected');
}

HistoryRoutePanel.isLastPage = function()
{
	return this._nCount == this.totalNum;
}

HistoryRoutePanel.selectRow = function(rowNo)
{
	this.hisDataGrid.datagrid('selectRow',rowNo);
}

HistoryRoutePanel.stopPlay = function(rowNo)
{
	this._isOver = true;
	HistoryRoutePanel.resetButton();	 
	$("#btnPlayRoute").linkbutton('enable');
	 
	window.clearInterval(this.timerId);
	this.timerId = null;
	this._intervalId = null;
	this.firstPlay = false;
	this._isPlay = false;
	this._nCount = 0;
	this._preLat = null;
	this._preLng = null;
	this._isOver = true;
	//this._playButton.html("播放");
	
    var mapHandler = this.routeMapHandler;
	if (mapHandler){
		mapHandler.drawStop();
	}
}

HistoryRoutePanel.play = function()
{
   if (!this._isPlay) {
	 this._isPlay = true;
	 this._isPause = false;
	   
	 $("#btnPauseRoute").linkbutton('enable');
	 $("#btnPlayRoute").linkbutton('disable');
	 
	 if (this._isOver == true) {
		 //重新播放时，清除掉原有的轨迹
		  this._isOver = false;
		this.firstPage();
		this.routeMapHandler.clearHisRoute(); //
		this.startPlayRoute(this.records);
		return;
	 }else
	 {
		 //从暂停处，开始播放
		 var me = this;
		 this.timerId = window.setInterval(function() {
						me.PlayWithoutGrid()
		 }, this.playSpeed);
	 }

   }

}

HistoryRoutePanel.pause = function()
{
	 $("#btnPauseRoute").linkbutton('disable');
	 $("#btnPlayRoute").linkbutton('enable');
	 this._isPlay = false;
	 this._isPause = true;
	 if (this.timerId != null) {
	     window.clearInterval(this.timerId);
		 this.timerId = null;
	 }

}
//得到历史轨迹回放的地图对象，调用baidu.jsp中的地图对象
HistoryRoutePanel.getHisMapHandler = function()
{
	 var iframeDom = $("#routeMapFrame")[0];
	 return iframeDom.contentWindow.OperatorObj;
}

 HistoryRoutePanel.startPlayRoute = function(records)
 {
	 if(this.routeMapHandler == null)
		 return;
	 this.records = records;
	 //播放车辆轨迹前，先一次性生成轨迹
	 if(this.routeMapHandler.showRouteBeforePlay==true)
	 {
	    this.routeMapHandler.drawHisRoute(records);
	 }
	 $("#btnQueryHisData").linkbutton('disable');
	 $("#btnStopPlayRoute").linkbutton('enable');
	 $("#btnPauseRoute").linkbutton('enable');
     HistoryRoutePanel.setButtonText("btnQueryHisData","正在回放..");
	 
	 //this.routeMapHandler.setGrid(this);
	 this.routeMapHandler._playButton = $("#btnPlayRoute");
	 

	// var playSpeed = $('#playSpeed').slider("getValue");//播放速度
	 //var maxTimeOut = 200;
	 //this._nTimeOut = (maxTimeOut - parseInt(playSpeed));
     //var total = options.total;  
	 var curPageData = this.getCurPageData();
	 var curPageSize = curPageData.length;
	 this.totalNum = records.length;
	 this._nCurrentPageSize = curPageSize;

	//author：shinoin
	//date：2019-3-4
	//修改代码
	 if(this.playOrder){
		 this._nCount = 0 ;
	 }else{
		 //反向播放
		 this._nCount = this.totalNum -1;
	 }
	 this._isOver = false;
	 this._isPause = false;
	 this.autoChangePage = (true);
	 var me = this;
	 if(this.timerId)
	 {
		 routeMapHandler.drawStop();
		 this._timerId = null;
	 }
	 //console.log("创建计时器:"+ routeMapHandler.timerId);
	 this.timerId = setInterval(
					function(){
						me.PlayWithoutGrid();
					},
					this.playSpeed);
			
	 
 }


 HistoryRoutePanel.convertRecord = function(rd)
 {
     // var vehicleInfo = {id:rd.ID, text:rd.plateNo, vehicleId:rd.ID, rLat:rd.latitude,rLng:rd.longitude, tLat:rd.latitude, tLng:rd.longitude,status:rd.status,color:rd.plateColor,validate:rd.valid,direction:rd.direction,
							//  angleInt:rd.direction, statusInt:0, speed:rd.velocity, warnTypeId:0, online:rd.online};
	 // return vehicleInfo;

 }

 
 HistoryRoutePanel.PlayWithoutGrid = function() {
	 if(this._isOver)
		 return;
	
		if (this.isLastPage() == true) {
			 this.stopPlay();//播放结束
			 return;
		}
		if (!this._isPlay)
			this._isPlay = true;
			//设置表格显示正在播放的行上
		//this._gridSelectionModel.select(this._nCount, true);
		this.selectRow(this._nCount);
			//var index = this._nCount + (this._nCurrentPage - 1) * this._defaultPageSize;
		var record = this.records[this._nCount];
		if (record) 
			{
				record.online = true;
				this.routeMapHandler.drawRoute(record);//画出历史轨迹
				if(this.totalNum > 0)
				{
					var progress = parseInt(100 * (record.RowNum / this.totalNum));
					this.setProgress(progress);
				}
			}
		//author：shinoin
		//date：2019-3-4
		//修改代码
		if(this.playOrder){
			this._nCount++;
		}else{
			//反向播放
			this._nCount --;
		}
}



 HistoryRoutePanel.PlayWithGrid = function() {
	 if(this._isOver)
		 return;
	
		if (this._nCount == this._nCurrentPageSize) {
			//当前页的记录已经播放完毕，需要翻页，继续播放
			if (this.isLastPage() == false) {
				if (this._autoChangePage) {
					this._nCount = 0;
					this._isPlay = false;
					if (this.timerId != null) {
						window.clearInterval(this.timerId);
						this.timerId = null;
					}
					this.nextPage();
				} else {
					//this._drawPlayWithGrigEnd();
				}
			} else {
				this.stopPlay();//播放结束
			}
		} else {

			if (!this._isPlay)
				this._isPlay = true;
			//设置表格显示正在播放的行上
			//this._gridSelectionModel.select(this._nCount, true);
			this.selectRow(this._nCount);
			//var index = this._nCount + (this._nCurrentPage - 1) * this._defaultPageSize;
			var record = this.getCurRowData();
			if (record) {
				record.online = true;
				this.routeMapHandler.drawRoute(record);//画出历史轨迹
				if(this.totalNum > 0)
				{
					var progress = parseInt(100 * (record.RowNum / this.totalNum));
					this.setProgress(progress);
				}
			}
		}
		this._nCount++;
}

/**
 *	填充历史轨迹回放功能中的车牌号
 *  调用来源：viewRealData.jsp，点击回放按钮，开始调用 
 * 
 */

function setHisRoutePlateNo(plateNo){
	// console.log("开始设置历史轨迹中的车牌号 : " + plateNo);
	if($("#routePlateNo")){
		$("#routePlateNo").textbox('setValue', plateNo);
	}
}
